package com.zxt.lock.config;


import com.alibaba.fastjson.JSON;
import com.zxt.factory.YamlPropertySourceFactory;
import com.zxt.lock.RedissonLock;
import com.zxt.lock.RedissonManager;
import com.zxt.lock.properties.RedissonProperties;
import org.redisson.Redisson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.*;
import org.springframework.core.annotation.Order;

/**
 * 触发spring.factories
 * 第一步:会通过配置的属性工厂来读取配置到配置属性类
 * 第二步:将配置类交给我们的redisson工厂进行生产Config配置类
 * 第三步:redisson工厂会根据配置的不同类型选择不同的策略模式(集群，单机)
 * 第四步:将工厂模式生产出的Config配置类交给 Redisson官方类提供的create方法进行创建
 * 第五步:通过以上初始化出的redisson,初始化出需要的redisson工具类
 *
 * @author zxt
 */
@Configuration
@ConditionalOnClass({Redisson.class})
@EnableConfigurationProperties({RedissonProperties.class})
@ComponentScan(basePackages = "com.zxt.lock")
@PropertySource(
        factory = YamlPropertySourceFactory.class,
        value = {"classpath:zxt-lock.yml"}
)
public class LockAutoConfiguration {
    private static final Logger log = LoggerFactory.getLogger(LockAutoConfiguration.class);

    public LockAutoConfiguration() {
    }

    @Bean
    @ConditionalOnMissingBean
    @Order(2)
    public RedissonLock redissonLock(RedissonManager redissonManager) {
        RedissonLock redissonLock = new RedissonLock();
        redissonLock.setRedissonManager(redissonManager);
        log.info("RedissonLock组装完毕");
        return redissonLock;
    }

    @Bean
    @ConditionalOnMissingBean
    @Order(1)
    public RedissonManager redissonManager(RedissonProperties redissonProperties) {
        RedissonManager redissonManager = new RedissonManager(redissonProperties);
        log.info("RedissonManager组装完毕,连接信息={}", JSON.toJSONString(redissonProperties));
        return redissonManager;
    }
}
